package com.kensaka.todo.dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class TodoDbAdapter {

	
	// Dtabase fields
	public static final String KEY_ROWID = "_id";
	public static final String KEY_CATEGORY = "category";
	public static final String KEY_SUMMARY  = "summary";
	public static final String KEY_DESCRIPTION = "description";
	public static final String KEY_UPDATE_TIME = "lastUpdateTime";
	public static final String KEY_WEIGHT = "weight";
	public static final String DB_TABLE="todo";
	
	private Context context;
	private SQLiteDatabase db;
	private TodoDatabaseHelper dbHelper;
	
	public TodoDbAdapter(Context context) {
		this.context = context;
	}
	
	public TodoDbAdapter open() throws SQLException {
		dbHelper = new TodoDatabaseHelper(context);
		db = dbHelper.getWritableDatabase();
		return this;
	}
	
	public void close (){
		dbHelper.close();
	}
	
	private ContentValues createContentValues(String category, String summary, String description, String weight){
		ContentValues values = new ContentValues();
		values.put(KEY_CATEGORY, category);
		values.put(KEY_SUMMARY, summary);
		values.put(KEY_DESCRIPTION, description);
		values.put(KEY_UPDATE_TIME, System.currentTimeMillis());
		values.put(KEY_WEIGHT, weight);
		return values;
	}
	
	
	/**
	 * Create a new todo if the todo is successfully created return the new orwId for that note,
	 * otherwise return a -1 to indicate failure.
	 * @param category
	 * @param summary
	 * @param description
	 * @return
	 */
	public long createTodo(String category, String summary, String description, String weight){
		ContentValues values	 = createContentValues(category, summary, description, weight);
		return db.insert(DB_TABLE,null,values);
	}

	
	/**
	 * update the todo
	 * @param category
	 * @param summary
	 * @param description
	 * @return
	 */
	public boolean updateTodo(long rowId, String category, String summary, String description, String weight){
		// Testing svm version control.
		ContentValues values = createContentValues(category, summary, description,weight);
		return db.update(DB_TABLE, values, KEY_ROWID+"="+rowId, null) > 0;
	}
		
	
	public boolean deleteTodo(long rowId) {
		return db.delete(DB_TABLE, KEY_ROWID +"="+rowId, null) > 0;
	}
	
	public Cursor fetchAllTodos() {
		return db.query(DB_TABLE, new String [] {KEY_ROWID,KEY_CATEGORY,KEY_SUMMARY, KEY_DESCRIPTION,KEY_UPDATE_TIME, KEY_WEIGHT}, null ,null, null, null, null);
	}

	public Cursor fetchTodo(long rowId){
		Cursor mCursor = db.query(true, DB_TABLE, new String [] {KEY_ROWID,KEY_CATEGORY,KEY_SUMMARY, KEY_DESCRIPTION,KEY_UPDATE_TIME, KEY_WEIGHT}, KEY_ROWID+"="+rowId ,null, null,null, null, null);
		
		if (mCursor != null){
			mCursor.moveToFirst();
		}
		return mCursor;
	}
	
	
}
